package com.gitee.wsl.ext.string

import kotlin.math.max
import kotlin.math.min

/**
 * 尽量在pos位置两侧取文本，文本总长度不超过len
 */
fun shortText(str: CharSequence, pos: Int, len: Int): String {
    var pos = pos
    val n = str.length
    if (pos < 0) pos = n
    if (pos > str.length) return ""

    var start = max(pos - len / 2, 0)
    val end = min(start + len, n)
    start = min(max(0, n - len), start)

    val sb = StringBuilder(len + 2)
    if (pos < 0) {
        sb.append("[]")
    } else {
        if (start > 0) sb.append("...")
        sb.append(str, start, pos)
        sb.append('[')
        if (pos < n) {
            sb.append(str.get(pos))
        }
        sb.append(']')
    }
    if (pos < end) {
        sb.append(str, pos + 1, end)
    }
    if (end < n) sb.append("...")
    return sb.toString()
}